import { useState, useEffect, useRef, lazy, Suspense } from 'react'
import { Button, message, Modal, Popconfirm, Tree } from 'antd'
import { ImportOutlined, EditOutlined, DeleteOutlined, PlusOutlined, ExclamationCircleFilled } from '@ant-design/icons'
import LdPrintTable from '../../../../components/LdPrintTable'
import bus from '../../../../utils/eventBus'
import './index.scss'
const { confirm } = Modal
const UserDialog = lazy(() => import('./UserDialog'))
const AddDivision = lazy(() => import('./AddDivision'))
interface pageType {
    total: number,
    pageSize: number,
    currentPage: number
}
const UserManagement = () => {
    const [data, setData] = useState<any[]>([])
    const [treeData, setTreeData] = useState<any[]>([])
    const [userDialogShow, setUserDialogShow] = useState<boolean>(false)
    const [defaultSelectedKeys, setDefaultSelectedKeys] = useState<string[]>([])
    const [divisionShow, setDivisionShow] = useState<boolean>(false)
    const rowData = useRef<any>(undefined)
    const settingData = useRef<any>(undefined)
    const treeKey = useRef<string>('')
    const treeResolve = useRef<any>('')
    const nodeData = useRef<any>(null)
    const pageConfig = useRef<pageType>({
        total: 0,
        pageSize: 10,
        currentPage: 1
    })
    const columns = useRef([
        { key: 'name', dataIndex: 'name', title: "姓名", width: 100, ellipsis: true },
        { key: 'account', dataIndex: 'account', title: '账号', ellipsis: true },
        { key: 'permissionLabel', dataIndex: 'permissionLabel', title: '人员等级' },
        {
            key: 'action',
            dataIndex: 'action',
            title: '操作',
            width: 180,
            render: (_: any, record: any) => {
                return (
                    <>
                        <span onClick={() => handleTableEdit(record)}
                            style={{ cursor: 'pointer', marginRight: '19px', color: '#0e7de9', fontSize: '14px' }}>编辑</span>
                        <Popconfirm title='确认要重置该成员密码?' placement="topLeft" onConfirm={() => handleMakeup(record)}>
                            <span style={{ cursor: 'pointer', marginRight: '19px', color: '#0e7de9', fontSize: '14px' }}
                            >重置密码</span>
                        </Popconfirm>

                        <Popconfirm title='确认要删除该成员?' placement="topLeft" onConfirm={() => handleUserDelete(record)}>
                            <span
                                style={{ cursor: 'pointer', color: '#0e7de9', fontSize: '14px' }}>删除</span>
                        </Popconfirm>
                    </>
                )
            }
        }
    ])
    const handlePage = (data: pageType) => {
        pageConfig.current = { ...pageConfig.current, ...data }
        loadTableData(defaultSelectedKeys[0])
    }
    const handleTableEdit = (data: any) => {
        rowData.current = { ...data }
        setUserDialogShow(true)
    }
    const handleMakeup = (data: any) => {
        window.chromePro.resetPassword(JSON.stringify({ id: data.id }));
    }
    const handleImport = () => {
        window.chromePro.importCardBatch();
    }
    const handleDivEdit = () => {
        if (!defaultSelectedKeys.length) return message.warning('请先选择组织机构在操作')
        dialogFn(nodeData.current, 2)
    }
    const dialogFn = (row: any, type: number) => {
        if (type === 1) {
            settingData.current = {id:row.id,type};
        } else {
            settingData.current = { ...row, type };
        }
        setDivisionShow(true)
    }
    const handleDelete = () => {
        if (!defaultSelectedKeys.length) return message.warning('请选择您想要删除的机构')
        confirm({
            title: '提示',
            icon: <ExclamationCircleFilled />,
            content: '确认要删除该组织机构?',
            okText: '确认',
            cancelText: '取消',
            onOk() {
                window.chromePro.delDepartment(JSON.stringify({ id: defaultSelectedKeys[0] }));
            },
            onCancel() {
                message.info('已取消')
            }
        })
    }
    const handleAdd = () => {
        dialogFn(nodeData.current, 1)
    }
    const onLoadData = ({ key = '', children, id = '' }: any) => {
        return new Promise<void>(resolve => {
            treeResolve.current = resolve
            if (children) {
                resolve();
                return
            }
            const params = {
                id: id ? id : '',
            };
            treeKey.current = key
            window.chromePro.getDepartmentList(JSON.stringify(params));
        })
    }
    const handleUserAdd = () => {
        if (!defaultSelectedKeys.length) return message.warning('请先选择组织机构!!!')
        rowData.current = null
        setUserDialogShow(true)
    }
    const getDepartmentListFinished = (res: any) => {
        if (res.code === 200) {
            if (!res.data.length) return treeResolve.current && treeResolve.current()
            res.data.map((item: any) => {
                item.title = item.name
                item.key = item.id
            })
            setTreeData(origin => {
                if (!origin.length) {
                    pageConfig.current = { ...pageConfig.current, currentPage: 1 }
                    loadTableData(res.data[0].id)
                }
                return updateTreeData(origin, treeKey.current, [...res.data])
            })
            if (!treeData.length) {
                nodeData.current = { ...res.data[0] }
                setDefaultSelectedKeys([res.data[0].id])
            }
            treeResolve.current && treeResolve.current()
        } else {
            message.error(res.msg)
        }
    }
    const updateTreeData = (list: any[], key: string, children: any[]): any[] => {
        if (!key) {
            return [...children]
        }
        return list.map(node => {
            if (node.key === treeKey.current) {
                return {
                    ...node,
                    children
                }
            }
            if (node.children) {
                return {
                    ...node,
                    children: updateTreeData(node.children, key, children)
                }
            }
            return {
                ...node
            }
        })
    }
    const handleSelect = (key: any, el: any) => {
        nodeData.current = { ...el.node }
        const [id] = key
        if (id) {
            pageConfig.current = { ...pageConfig.current, currentPage: 1 }
            setDefaultSelectedKeys([id])
            loadTableData(id)
        }
    }
    const loadTableData = (id: string) => {
        const params = {
            id,
            ...pageConfig.current
        }
        window.chromePro.getUserList(
            JSON.stringify(params)
        );
    }
    const getUserListFinished = (data: any) => {
        if (data.code === 200) {
            data.data.map((item: any) => {
                item.permissionLabel = item.permission == 4 ? '一般涉密' :
                    item.permission == 5 ? '重要涉密' :
                        item.permission == 6 ? '核心涉密' :
                            item.permission == 0 ? '普通用户' : '管理员'
            })
            pageConfig.current = { ...pageConfig.current, total: data.total }
            setData(data.data)
        } else {
            message.error(data.msg);
        }
    }
    const delDepartmentFinished = (data: any) => {
        if (data.code === 200) {
            message.success(data.msg);
            setTreeData([])
            onLoadData({})
        } else {
            message.error(data.msg);
        }
    }
    const handleUserDelete = (row: any) => {
        window.chromePro.delUser(
            JSON.stringify({
                id: row.id,
            })
        );
    }
    const delUserFinished = (data: any) => {
        if (data.code === 200) {
            message.success(data.msg);
            pageConfig.current = { ...pageConfig.current, currentPage: 1 }
            setDefaultSelectedKeys(origin => {
                loadTableData(origin[0])
                return origin
            })
        } else {
            message.error(data.msg);
        }
    }
    const resetPasswordFinished = (data: any) => {
        if (data.code === 200) {
            message.success(data.msg);
            pageConfig.current = { ...pageConfig.current, currentPage: 1 }
            setDefaultSelectedKeys(origin => {
                loadTableData(origin[0])
                return origin
            })
        } else {
            message.error(data.msg);
        }
    }
    const importCardBatchFinished = (data: any) => {
        if (data.code === 200) {
            onLoadData({})
            message.success(data.msg);
        } else {
            message.error(data.msg);
        }
    }
    const closeUserDialog = () => {
        setUserDialogShow(false)
    }
    const handleUserSuccess = () => {
        pageConfig.current = { ...pageConfig.current, currentPage: 1 }
        loadTableData(defaultSelectedKeys[0])
    }
    const handleSuccess = () => {
        setTreeData([])
        onLoadData({})
    }
    const closeDivision = ()=>{
        setDivisionShow(false)
    }
    useEffect(() => {
        onLoadData({})
        bus.addListener("delUserFinished", delUserFinished);
        bus.addListener("resetPasswordFinished", resetPasswordFinished);
        bus.addListener("getDepartmentListFinished", getDepartmentListFinished);
        bus.addListener("getUserListFinished", getUserListFinished);
        bus.addListener("delDepartmentFinished", delDepartmentFinished);
        bus.addListener("importCardBatchFinished", importCardBatchFinished);
    }, [])
    useEffect(() => {
        return () => {
            bus.removeListener("delUserFinished", delUserFinished);
            bus.removeListener("resetPasswordFinished", resetPasswordFinished);
            bus.removeListener("getDepartmentListFinished", getDepartmentListFinished);
            bus.removeListener("getUserListFinished", getUserListFinished);
            bus.removeListener("delDepartmentFinished", delDepartmentFinished);
            bus.removeListener("importCardBatchFinished", importCardBatchFinished);
        }
    }, [])
    return (
        <>
            <div className="user-box">
                <div className="user-left">
                    <div className="header">
                        <span style={{ fontSize: '18px', color: '#333333', fontWeight: 600 }}>机构</span>
                        <div style={{ marginRight: '45px', color: '#1890ff' }} className="btn-edit" onClick={handleImport}>
                            <ImportOutlined />
                        </div>
                        <div className="setting-btn">
                            <div className="btn-edit" style={{ color: '#1890ff' }} onClick={handleDivEdit}>
                                <EditOutlined />
                            </div>
                            <div className="btn-two" style={{ color: 'red' }} onClick={handleDelete}>
                                <DeleteOutlined />
                            </div>
                            <div className="btn-three" style={{ color: '#1890ff' }} onClick={handleAdd}>
                                <PlusOutlined />
                            </div>
                        </div>
                    </div>
                    {
                        treeData.length ?
                            <Tree className='useTree' onSelect={handleSelect} blockNode={true} defaultSelectedKeys={defaultSelectedKeys} treeData={treeData} loadData={onLoadData}></Tree> :
                            null
                    }
                </div>
                <div className="user-right">
                    <div className="table-header">
                        <span style={{ fontWeight: 600, fontSize: '18px' }}>成员</span>
                        <Button type="primary" onClick={handleUserAdd} className="btn">
                            新增人员</Button>
                    </div>
                    <div style={{ height: 'calc(100% - 50px)' }}>
                        <LdPrintTable rowSelection={false} data={data} pageConfig={pageConfig.current} columns={columns.current} handlePage={handlePage}></LdPrintTable>
                    </div>
                </div>
            </div>
            <Suspense>
                {
                    userDialogShow ? <UserDialog row={rowData.current} nodeData={defaultSelectedKeys[0]} success={handleUserSuccess} close={closeUserDialog} /> : null
                }
                {
                    divisionShow ? <AddDivision row={settingData.current}
                        success={handleSuccess}
                        close={closeDivision} /> : null
                }
            </Suspense>
        </>
    )
}
export default UserManagement